package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.query.TravelConfition;
import cn.wolfcode.wolf2w.query.TravelQuery;
import cn.wolfcode.wolf2w.redis.IUserRedisService;
import cn.wolfcode.wolf2w.repository.TravelRepsitory;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.DBHelper;
import com.mongodb.DB;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Optional;

//旅游日记
@Service
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private TravelRepsitory travelRepsitory;

    @Autowired
    private MongoTemplate template;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IDestinationService destinationService;

    @Autowired
    private IUserRedisService userRedisService;


    //容易让mongodb产生误会,后续自动生成的id不会存进去
    @Override
    public void save(Travel travel) {
        travel.setId(null);
        travelRepsitory.save(travel);
    }

    @Override
    public void update(Travel travel) {
        travelRepsitory.save(travel);
    }

    @Override
    public void delete(String id) {
        travelRepsitory.deleteById(id);
    }

    @Override
    public Travel get(String id) {
        if (StringUtils.hasLength(id)) {
            //获取操作对象
            Optional<Travel> optional = travelRepsitory.findById(id);
            if (optional.isPresent()) {
                //获取实例对象
                Travel travel = optional.get();
                //设置头像给前端调用
                travel.setAuthor(userInfoService.get(travel.getUserId()));
                //设置用户数据给前端调用
                Destination destination = destinationService.get(travel.getDestId());
                travel.setDest(destination);
                return travel;
            }
        }
        return null;
    }

    @Override
    public List<Travel> list() {
        return travelRepsitory.findAll();
    }

    //查询页面数据
    @Override
    public Page<Travel> query(TravelQuery qo) {
        Query query = new Query();
        //根据目的地查询
        if (StringUtils.hasLength(qo.getDestId())) {
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }
        //查询出行天数
        TravelConfition day = TravelConfition.DAY_MAP.get(qo.getDayType());
        if (day != null) {
            query.addCriteria(Criteria.where("day").gte(day.getMin()).lte(day.getMax()));
        }
        //查询人均消费
        TravelConfition per = TravelConfition.PEREXPEND_MAP.get(qo.getPerExpendType());
        if (per != null) {
            query.addCriteria(Criteria.where("perExpend").gte(per.getMin()).lte(per.getMax()));
        }
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize()
                , Sort.Direction.ASC, "_id");
        //最新,最热
        if (qo.getOrderType() == TravelQuery.ORDER_NEW) {
            pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize()
                    , Sort.Direction.DESC, "createTime");
        } else if (qo.getOrderType() == TravelQuery.ORDER_HOT) {
            pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize()
                    , Sort.Direction.DESC, "viewnum");
        }
        Page<Travel> page = DBHelper.query(query, Travel.class, template, pageable);
        //设置用户数据
        for (Travel travel : page) {
            travel.setAuthor(userInfoService.get(travel.getUserId()));
            System.out.println(travel.getUserId());
        }
        return page;
    }


    //游记发布新增或修改数据
    //HttpServletRequest request:请求数据
    @Override
    public void saveOrUpdate(Travel travel, HttpServletRequest request) {
        //补全保存的数据
        //设置目的地名字
        Destination destination = destinationService.get(travel.getDestId());
        travel.setDestName(destination.getName());
        //设置用户id
        String token = request.getHeader("token");
        UserInfo user = userRedisService.getUserByToken(token);
        System.out.println(user.getId());
        travel.setUserId(user.getId());
        if (!StringUtils.hasText(travel.getId())) {
            //设置创建时间
            travel.setCreateTime(new Date());
            //设置发布时间
            travel.setReleaseTime(new Date());
            //设置最后修改时间
            travel.setLastUpdateTime(new Date());
            //保存
            this.save(travel);
        } else {
            //修改
            this.update(travel);
        }
    }


    //游记审核操作
    @Override
    public void audit(String id, int state) {
        //获取游记对象
        Travel travel = this.get(id);
        //判断状态
        if (travel.getState() == Travel.STATE_WAITING && travel == null) {
            throw new LogicException("参数异常");
        }
        //审核通过后操作,2
        if (state == Travel.STATE_RELEASE) {
            //通过后修改最新更新时间
            travel.setLastUpdateTime(new Date());
            //通过后修改发布时间
            travel.setReleaseTime(new Date());
            //修改游记状态,2
            travel.setState(Travel.STATE_RELEASE);
        } else {
            //审核未通过后操作
            //修改游记状态 3
            travel.setState(Travel.STATE_REJECT);
            //通过后修改最新更新时间
            travel.setLastUpdateTime(new Date());
        }
        //修改
        this.update(travel);
    }


    //查询出游记前三
    @Override
    public List<Travel> viewnumTop3(String destId) {
        Pageable pageable = PageRequest.of(0, 3, Sort.Direction.DESC, "viewnum");
        List<Travel> travels = travelRepsitory.findByDestId(destId, pageable);
        return travels;
    }

    //查询目的地下游记
    @Override
    public List<Travel> queryByDestId(String id) {
        List<Travel> list = travelRepsitory.findByDestId(id, null);
        for (Travel travel : list) {
            travel.setAuthor(userInfoService.get(travel.getUserId()));
        }
        return list;
    }
}
